package com.dataaccess.dataaccess.web.service;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dataaccess.dataaccess.common.base.BaseService;
import com.dataaccess.dataaccess.common.utils.appkit.ConfigKit;
import com.dataaccess.dataaccess.support.model.RespEntity;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

@Service
@Slf4j
public class UploadService extends BaseService {

	protected String[] FILE_UPLOAD_IMG_EXTS = { "jpg", "png", "gif", "jpeg", "bmp", "zip","xlsx","txt","docx","doc","xls","jar","mp4"};

	public Object uploadFile(@RequestParam Map<String, Object> params, HttpServletRequest request) {
		List<String> fileNameLsit = new ArrayList<String>();
		List<Map<String,Object>> list = new ArrayList<>();
		Map<String,Object> errorMap = new HashMap<>();
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (!commonsMultipartResolver.isMultipart(request)) {
			errorMap.put("errorMsg","无法从Request中获取文件对象");
			return errorMap;
		}
		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
		Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
		String paths = "";
		while (fileNames.hasNext()) {
			Map<String,Object> fileMap = new HashMap<>();
			String fileName = fileNames.next();
			MultipartFile multipartFile = multipartHttpServletRequest.getFile(fileName);
			if (multipartFile == null) {
				errorMap.put("errorMsg",StrUtil.format("未成功获取文件对象", fileName));
				return errorMap;
			} else if (multipartFile.isEmpty()) {
				errorMap.put("errorMsg",StrUtil.format("成功获取文件对象,但无法获取名为{}的文件", fileName));
				return errorMap;
			}
			String repath = ConfigKit.getStr("fileSavePath", "upload")+"/"+ DateUtil.now().split(" ")[0].replace("-","");
			StringBuffer url = request.getRequestURL();
			//String webPath = url.toString().replace("/uploads", "/download?fileName=");
			String webPath = ConfigKit.getStr("webPath", "upload")+ DateUtil.now().split(" ")[0].replace("-","")+"/";
			// 原始文件名
			String oldFileName = multipartFile.getOriginalFilename();
			String[] arrTmp = oldFileName.split("\\.");
			String ext = arrTmp[arrTmp.length - 1];
			int count = 0;
			for (String _ext : FILE_UPLOAD_IMG_EXTS) {
				if (_ext.equalsIgnoreCase(ext)) {
					count++;
				}
			}
			if (count < 1) {
				return RespEntity.fail(StrUtil.format("文件后缀{}不合法", ext));
			}
			String newFileName = System.currentTimeMillis() + "." + ext;
			File file = new File(repath);
			if (!file.exists()) {
				file.mkdirs();
			}
			file = new File(repath + "/" + newFileName);
			try {
				multipartFile.transferTo(file);
				//fileNameLsit.add(webPath + newFileName);
				fileMap.put("filePath",webPath + newFileName);
				fileMap.put("fileName",multipartFile.getOriginalFilename());
				list.add(fileMap);
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
				errorMap.put("errorMsg",StrUtil.format("图片保存失败:{}", e.getMessage()));
				return errorMap;
			}
		}
		return list;
	}


	/**
	 * @Author YangYu
	 * @Description 文件上传
	 * @Date Created in 11:23 2021/11/19
	 * @Param [request]
	 */

	public JSONObject uploadFiles(HttpServletRequest request,String folderName) {

		//错误信息
		//Map<String, Object> errorMap = new HashMap<>();
		JSONObject errorMap = new JSONObject();
		CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (!commonsMultipartResolver.isMultipart(request)) {
			errorMap.put("errorMsg", "无法从Request中获取文件对象");
			return errorMap;
		}
		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
		Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
		String paths = "";
		//Map<String, Object> fileMap = new HashMap<>();
		JSONObject fileMap = new JSONObject();
		while (fileNames.hasNext()) {
			String fileName = fileNames.next();
			MultipartFile multipartFile = multipartHttpServletRequest.getFile(fileName);
			if (multipartFile == null) {
				errorMap.put("errorMsg", StrUtil.format("未成功获取文件对象", fileName));
				return errorMap;
			} else if (multipartFile.isEmpty()) {
				errorMap.put("errorMsg", StrUtil.format("成功获取文件对象,但无法获取名为{}的文件", fileName));
				return errorMap;
			}
			// 原始文件名
			String oldFileName = multipartFile.getOriginalFilename();
			String repath = ConfigKit.getStr("fileSavePath", "upload")+"/"+folderName+"/"+ DateUtil.now().split(" ")[0].replace("-","")+"/";
			//String repath = "e:/"+folderName+"/"+ DateUtil.now().split(" ")[0].replace("-","")+"/";
			StringBuffer url = request.getRequestURL();
			String webPath = ConfigKit.getStr("webPath", "upload")+folderName+"/" + DateUtil.now().split(" ")[0].replace("-", "") + "/";
			String[] arrTmp = oldFileName.split("\\.");
			String ext = arrTmp[arrTmp.length - 1];
			int count = 0;
			for (String _ext : FILE_UPLOAD_IMG_EXTS) {
				if (_ext.equalsIgnoreCase(ext)) {
					count++;
				}
			}
			if (count < 1) {
				return errorMap.put("error",StrUtil.format("文件后缀{}不合法", ext));
			}
			//新文件名
			//String newFileName = number + "." + ext;
			File file = new File(repath);
			if (!file.exists()) {
				file.mkdirs();
			}
			file = new File(repath + oldFileName);
			try {
				multipartFile.transferTo(file);
				fileMap.put("filePath", webPath + oldFileName);
				fileMap.put("fileName", multipartFile.getOriginalFilename());
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
				errorMap.put("errorMsg", StrUtil.format("图片保存失败:{}", e.getMessage()));
				return errorMap;
			}
		}
		return fileMap;
	}

	/**
	 * @Author YangYu
	 * @Description 海康控梯获取图片
	 * @Date Created in 15:40 2021/3/25
	 * @Param [picUrl]
	 */

	public  String GetCameraPreviewURL(String picUrl) throws IOException {

		/**
		 * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
		 */
		ArtemisConfig.host = "122.4.227.102:4433"; // artemis网关服务器ip端口
		ArtemisConfig.appKey = "24769112";  // 秘钥appkey
		ArtemisConfig.appSecret = "NxjYIfempoqQaVtRqKLF";// 秘钥appSecret

		/**
		 * STEP2：设置OpenAPI接口的上下文
		 */
		final String ARTEMIS_PATH = "/artemis";

		/**
		 * STEP3：设置接口的URI地址
		 */
		final String previewURLsApi = ARTEMIS_PATH + "/api/frs/v1/application/picture";
		Map<String, String> path = new HashMap<String, String>(2) {
			{
				put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
			}
		};

		/**
		 * STEP4：设置参数提交方式
		 */
		String contentType = "application/json";

		/**
		 * STEP5：组装请求参数
		 */
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("url", picUrl);
		String body = jsonBody.toString();
		/**
		 * STEP6：调用接口
		 */
		// post请求application/json类型参数
		HttpResponse result = ArtemisHttpUtil.doPostStringImgArtemis(path, body, null, null, contentType , null);
		InputStream inputStream = result.getEntity().getContent();
		String newFileName = System.currentTimeMillis() + ".jpg";
		//String repath = ConfigKit.getStr("fileSavePath", "upload")+"/"+ DateUtil.now().split(" ")[0].replace("-","")+"/"+newFileName;
		String repath = ConfigKit.getStr("fileSavePath", "upload")+"/"+ DateUtil.now().split(" ")[0].replace("-","");
		File file = new File(repath);
		if (!file.exists()) {
			file.mkdirs();
		}
		file = new File(repath + "/" + newFileName);
		copyInputStreamToFile(inputStream, file);
		String webPath = ConfigKit.getStr("webPath", "upload")+ DateUtil.now().split(" ")[0].replace("-","")+"/"+newFileName;
		return webPath;
	}

	/**
	 * @Author YangYu
	 * @Description 海康视频事件图片查询（svrIndexCode 图片存储服务器唯一标识，提供picUri处会提供此字段, picUri 图片的相对地址）
	 * @Date Created in 10:00 2022/9/26
	 * @Param [svrIndexCode, picUri]
	 */

	public  String queryHkVideoImage(String svrIndexCode, String picUri) throws IOException {
		/**
		 * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
		 */
		ArtemisConfig.host = "122.4.227.102:4433"; // artemis网关服务器ip端口
		ArtemisConfig.appKey = "24769112";  // 秘钥appkey
		ArtemisConfig.appSecret = "NxjYIfempoqQaVtRqKLF";// 秘钥appSecret

		/**
		 * STEP2：设置OpenAPI接口的上下文
		 */
		final String ARTEMIS_PATH = "/artemis";

		/**
		 * STEP3：设置接口的URI地址
		 */
		final String previewURLsApi = ARTEMIS_PATH + "/api/video/v1/events/picture";
		Map<String, String> path = new HashMap<String, String>(2) {
			{
				put("https://", previewURLsApi);//根据现场环境部署确认是http还是https
			}
		};

		/**
		 * STEP4：设置参数提交方式
		 */
		String contentType = "application/json";

		/**
		 * STEP5：组装请求参数
		 */
		JSONObject jsonBody = new JSONObject();
		jsonBody.put("svrIndexCode", svrIndexCode);
		jsonBody.put("picUri", picUri);
		jsonBody.put("netProtocol", "http");
		String body = jsonBody.toString();
		/**
		 * STEP6：调用接口
		 */
		String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType, null);// post请求application/json类型参数
		JSONObject jsonObject = JSONUtil.parseObj(result);
		InputStream inputStream = new URL(jsonObject.getJSONObject("data").getStr("picUrl")).openStream();
		String newFileName = System.currentTimeMillis() + ".jpg";
		String repath = ConfigKit.getStr("fileSavePath", "upload") + "/" + DateUtil.now().split(" ")[0].replace("-", "");
		File file = new File(repath);
		if (!file.exists()) {
			file.mkdirs();
		}
		file = new File(repath + "/" + newFileName);
		copyInputStreamToFile(inputStream, file);
		String webPath = ConfigKit.getStr("webPath", "upload") + DateUtil.now().split(" ")[0].replace("-", "") + "/" + newFileName;
		return webPath;
	}
	// InputStream -> File
	private static void copyInputStreamToFile(InputStream inputStream, File file)throws IOException {
		try (FileOutputStream outputStream = new FileOutputStream(file)) {
			int read;
			byte[] bytes = new byte[1024];
			while ((read = inputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, read);
			}
		}

	}
}
